package com.likai.blog.controller;

import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.likai.blog.pojo.Blog;
import com.likai.blog.service.IBlogService;

/**
 * 主页Controller
 * @author likai
 *
 */

@Controller
public class IndexController {

	@Autowired
	@Qualifier("blogService")
	private IBlogService blogService ;
	
	@RequestMapping(value="/index")
	public ModelAndView index(
			Blog po,
			Integer page
			) {
		if(page == null) {
			page = 1 ;
		}
		ModelAndView mv = new ModelAndView() ;
		
		PageHelper.startPage(page, 10) ;
		List<Blog> blogList = blogService.findList(po) ;
		
		for (Blog blog : blogList) {
			List<String> imageList = blog.getImageList() ;
			String blogInfo = blog.getContent() ;
			//获取解析后的文档
			Document doc = Jsoup.parse(blogInfo) ;
			//取得后缀为jpg的img元素
			Elements jpgs = doc.select("img[src$=.jpg]") ;
			//循环取得每一个jpg并存入blog的imageList属性
			for(int x = 0 ; x < jpgs.size() ; x ++) {
				Element jpg = jpgs.get(x) ;
				imageList.add(jpg.toString()) ;
				//最多全三张
				if(x == 2) {
					break ;
				}
			}
		}
		 
		PageInfo pageInfo = new PageInfo(blogList,5) ;
		
		mv.addObject("pageInfo", pageInfo) ;
		
		mv.addObject("typeId",po.getTypeId()) ;
		
		mv.addObject("pageTitle", "博客首页") ;
		
		mv.addObject("releaseDateStr",po.getReleaseDateStr()) ;
		
		mv.addObject("mainPage", "/foreground/blog/list.jsp") ;
		
		mv.setViewName("mainTemp");
		
		return mv ;
	}
	
	
	/**
	 * 源码下载
	 * @return
	 */
	@RequestMapping(value="/download")
	public ModelAndView download() {
		ModelAndView mv = new ModelAndView() ;
		
		mv.addObject("mainPage", "/foreground/system/download.jsp") ;
		
		mv.addObject("pageTitle", "源码下载") ;
		
		mv.setViewName("mainTemp");
		return mv ;
	}
	
}
